// API 基础配置
// 在开发环境中使用代理，不需要基础URL
const API_BASE_URL = process.env.NODE_ENV === 'development' ? '' : (process.env.API_BASE_URL || 'http://localhost:9806')

// API 响应接口
export interface ApiResponse<T = any> {
  code: number
  msg: string
  payload?: T
}

// 登录请求参数
export interface LoginRequest {
  account: string
  pwd: string
  captcha: string
  csrf_token: string
}

// 登录响应数据
export interface LoginResponse {
  id: string
  account: string
  role_id: number[]
  status: number
  next: string
}

// 简单的API请求函数
export const apiRequest = async <T = any>(
  url: string,
  options: RequestInit = {}
): Promise<ApiResponse<T>> => {
  const fullUrl = API_BASE_URL + url
  console.log(`API请求: ${options.method || 'GET'} ${fullUrl}`)
  
  const defaultOptions: RequestInit = {
    credentials: 'include',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json'
    }
  }
  
  const mergedOptions = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers
    }
  }
  
  // 如果是POST请求，打印请求体（不包含敏感信息）
  if (options.method === 'POST' && options.body) {
    try {
      const body = JSON.parse(options.body as string)
      console.log('API请求体:', { ...body, pwd: body.pwd ? '***' : undefined })
    } catch (e) {
      console.log('API请求体:', options.body)
    }
  }
  
  try {
    console.log('发送API请求...')
    const response = await fetch(fullUrl, mergedOptions)
    console.log('API响应状态:', response.status)
    console.log('API响应头:', response.headers)
    
    // 检查响应的Cookie
    console.log('响应中的Set-Cookie头:', response.headers.get('set-cookie'))
    
    const data = await response.json()
    console.log('API响应数据:', data)
    
    return data
  } catch (error: any) {
    console.error('API请求错误:', error)
    
    return {
      code: 500,
      msg: error.message || '未知错误'
    }
  }
}

// 登录 API
export const loginApi = (data: LoginRequest) => {
  return apiRequest<LoginResponse>('/adm/passport/login', {
    method: 'POST',
    body: JSON.stringify(data)
  })
}

// 获取验证码
export const getCaptcha = () => {
  return `${API_BASE_URL}/adm/passport/captcha?r=${Math.random()}`
}

// 获取登录页面信息
export const getLoginInfo = () => {
  console.log("发送GET请求到/adm/passport/login获取登录信息...");
  const result = apiRequest<{
    csrf_token: string
    public_key: string
  }>('/adm/passport/login', {
    method: 'GET'
  });
  console.log("getLoginInfo函数返回的Promise:", result);
  return result;
}

// 检查登录状态
export const checkAuth = () => {
  return apiRequest('/adm/auth/check', {
    method: 'GET'
  })
}

// 退出登录
export const logout = () => {
  return apiRequest('/adm/passport/logout', {
    method: 'POST'
  })
}